package com.xyh.concurrency.example.atomic;

import com.xyh.concurrency.annoations.Recommend;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * 高并发原子性包
 * Atomic 包下面的所有类 cas
 */
@Slf4j
@Recommend
public class AtomicExample4 {
    /**
     * AtomicIntegerFieldUpdater 主要就是修饰原子性中类的某一个字段这个字段需要提供get方法
     * 并且使用volatile 还要不能被static 进行修饰
     */
    private static AtomicIntegerFieldUpdater<AtomicExample4> fieldUpdater =
            AtomicIntegerFieldUpdater.newUpdater(AtomicExample4.class, "count");
    @Getter
    public volatile int count = 100;

    public static void main(String[] args) {
        AtomicExample4 atomicExample4 = new AtomicExample4();
        if (fieldUpdater.compareAndSet(atomicExample4, 100, 120)) {
            log.info("update success :{}", atomicExample4.getCount());
        }
        if (fieldUpdater.compareAndSet(atomicExample4, 120, 100)) {
            log.info("update success :{}", atomicExample4.getCount());

        } else {
            log.info("update success :{}", atomicExample4.getCount());
        }
    }


}
